from Vector import *
from Ray import *
from math import sqrt

class Sphere:
  
  c = Vector()
  r = 1
  hit = []
  
  def __init__(self, _c=[0,0,0], r=1):
    self.c = Vector(_c)
    self.r = r
    hit = []

  def __str__(self): return "%s, r=%f" % (str(self.c), self.r)

  def Intersect(self, r):
    o_minus_c = r.o - self.c;                    # (o - c)
    
    a = r.d.ScalarProduct(r.d)                   # a = d^2
    p = r.d.ScalarProduct(o_minus_c) * 2         # p = 2d(o - c)
    r_q = self.r ** 2                            # r^2
    q = o_minus_c.ScalarProduct(o_minus_c) - r_q # q = (o - c)^2 - r^2

    discriminant = p*p - 4*a*q                   # p^2 - 4aq
    
    if (discriminant < 0): return False
    
    # ... and save the actual hit distances
    discriminant = sqrt(discriminant)            # sqrt()
   
    self.hit.append((-p - discriminant) / 2*a)   # enter/graze distance

    if (discriminant != 0):
      self.hit.append((-p + discriminant) / 2*a) # exit distance
      self.hit.sort()                            # sort hit-listing
    else:
      self.hit.append(0)                         # sphere grazed, no exit distance

    return True
